package org.jadelyre.core.codec;

import org.jadelyre.core.exception.CodecException;

import java.nio.ByteBuffer;

/**
 * 编码器
 */
public interface Codec {

    /**
     * 解码
     * @param byteBuffer
     * @return
     * @throws CodecException
     */
    Packet decode(ByteBuffer byteBuffer) throws CodecException;

    /**
     * 编码
     * @param packet
     * @return
     */
    ByteBuffer encode(Packet packet) throws CodecException;
//    default ByteBuffer encode(Packet packet) throws JadelyreException {
//        Header header = packet.getHeader();
//        if (header == null){
//            throw new JadelyreException("传输数据包头为空");
//        }
//        int headerLength = header.getHeaderLength();
//        if (headerLength < 0){
//            headerLength = 0;
//        }
//        if (header.getHeaderBytes() == null){
//            throw new JadelyreException("传输数据包头数据为空");
//        }
//        if (header.getHeaderBytes().length != headerLength){
//            throw new JadelyreException("传输数据包头占字节长度和表明的长度不一致");
//        }
//        if (packet.getBody() == null){
//            throw new JadelyreException("传输数据包体数据为空");
//        }
//        int neededLength = headerLength + packet.getBody().length;
//        ByteBuffer byteBuffer = ByteBuffer.allocate(neededLength);
//        byteBuffer.put(header.getHeaderBytes());
//        byteBuffer.put(packet.getBody());
//        byteBuffer.flip();
//        return byteBuffer;
//    }
}
